function PluVel = PluVelInspect(MR1,MR7,MV,d1,d2)
%PluVelInspect - Rainfall and velocity time series inspection and cleaning
%
%       PluVel = PluVelInspect(MR1,MR7,MV)
%       PluVel = PluVelInspect(MR1,MR7,MV,d1,d2)
%
% Let MR1 = [tR R1] and MR7 = [tR R7] be 1 d and 7 d cumulative rainfall 
% time series and MV = [tV V] a velocity time series with sampling rate of 
% 24 cpd (cycles per day).
% This function allows the time series inspection in order to verify the
% nature of the velocity peaks. The rainfall and velocity time series are 
% shown in two subplots and the user can zoom in the time series, leading 
% to a segment with one of these criteria:
%       ZOOM ON 30 DAYS TIME SERIES AROUND A SELECTED TIME
%       ZOOM ON 2 MONTH TIME SERIES AROUND A SELECTED TIME
%       ZOOM ON ONE YEAR TIME SERIES AROUND A SELECTED TIME
%       FREE CHOICE OF TIME LIMITS
% As a time series segment is selected, a figure with the zoom is shown and
% the user can verify if a possible velocity peak is real, i.e. rainfall
% triggered, or not. Moreover, a popup appears in the segment figure in 
% order to allow the interactive removal of possible false peaks.
%
% If d1 and d2 are defined and are MATLAB serial date numbers, they are 
% the limits of the rainfall time series.
% If d1 and d2 are undefined or empty, the considered limits are 
% max(tR(1),tV(1)) and min(tR(end),tV(end)). 
% 
% The output matrix PluVel = [t R1 V] is generated according to the user's 
% choices about the peak inspection and the management of time series 
% limits. 
%
%       PluVel = PluVelInspect(MR1,MR7,MV)
%       PluVel = PluVelInspect(MR1,MR7,MV,d1,d2)
%
% See also PluVelScalogram, trendClass, dataHomAug, dataTVT, TRLearnPluVel. 

% G. Teza, 2020

font_sz = 14;

tR = MR1(:,1);
tV = MV(:,1);

if nargin < 4 || isempty(d1)
    d1 = max([tR(1),tV(1)]);
end
if nargin < 5 || isempty(d2)
    d2 = min([tR(end),tV(end)]);
end

[~,IR1] = min(abs(tR-d1));
[~,IR2] = min(abs(tR-d2));
MR1 = MR1(IR1:IR2,:);
MR7 = MR7(IR1:IR2,:);

[~,IV1] = min(abs(tV-d1));
[~,IV2] = min(abs(tV-d2));
MV  = MV(IV1:IV2,:);

t = MV(:,1);

Ifig = 0;
while Ifig == 0
    
    strFigGen = sprintf('\nTime span from %s to % s\n',...
            datestr(d1),datestr(d2));
    fig1 = figure('name',strFigGen,'units','normalized','outerposition',[0 0 1 1]);  
      
    plotRV(MR1,MR7,MV,d1,d2);
    
    pp1 = uicontrol(fig1,'Style', 'popup',...
        'string', {'ZOOM ON 30 DAYS TIME SERIES AROUND A SELECTED TIME',...
        'ZOOM ON 2 MONTH TIME SERIES AROUND A SELECTED TIME',...
        'ZOOM ON ONE YEAR TIME SERIES AROUND A SELECTED TIME',...
        'FREE CHOICE OF TIME LIMITS','EXIT'},...
        'FontSize',font_sz,...
        'Units','normalized','Position', [0.05 0.4 0.18 0.1],...
        'Callback', 'uiresume(gcbf)');
    
    txt1 = uicontrol(fig1,'Style','text',...
        'Units','normalized','Position',[0.05 0.5 0.18 0.05],...
        'String','CLICK TO CHOOSE TIME','FontSize',font_sz);
    
    uiwait(fig1);
    
    vpp1 = pp1.Value;
    
    if vpp1 < 4
        
        if vpp1 == 1
            [tsi,~] = ginput(1);
            ts1 = tsi-15;
            ts2 = tsi+15;
        elseif vpp1 == 2
            [tsi,~] = ginput(1);
            ts1 = tsi-30;
            ts2 = tsi+30;
        elseif vpp1 == 3
            [tsi,~] = ginput(1);
            ts1 = tsi-183;
            ts2 = tsi+182;
        else 
            [tsi,~] = ginput(2);
            ts1 = tsi(1);
            ts2 = tsi(2);
        end
        ts1 = max(t(1),ts1);
        ts1 = floor(ts1);
        ts2 = min(t(end),ts2);
        ts2 = ceil(ts2);
        
        strFigSegm = sprintf(...
            '\nSelected segment of time series from %s to % s\n',...
            datestr(ts1),datestr(ts2)); 
        disp(strFigSegm);
        
        [~,IS1] = min(abs(t-ts1));
        [~,IS2] = min(abs(t-ts2));
        MR1S = MR1(IS1:IS2,:);
        MR7S = MR7(IS1:IS2,:);
        MVS = MV(IS1:IS2,:);
        
        fig2 = figure('name',strFigSegm,'units','normalized',...
            'outerposition',[0.25 0.25 0.7 0.7]);
        plotRV(MR1S,MR7S,MVS,ts1,ts2);
        pp2 = uicontrol(fig2,'Style', 'popup',...
            'string', {'INSPECTION OK','CLEAN A TIME SERIES SEGMENT'},...
            'FontSize',font_sz,...
            'Units','normalized','Position', [0.05 0.45 0.18 0.1],...
            'Callback', 'uiresume(gcbf)');
        uiwait(fig2);
        vpp2 = pp2.Value;
        if vpp2 == 2
            [tci,~] = ginput(2);
            tc1 = tci(1);
            tc2 = tci(2);
        end
        tc1 = max(t(1),tc1);
        tc1 = floor(tc1);
        tc2 = min(t(end),tc2);
        tc2 = ceil(tc2);
        options.Resize = 'on';
        options.WindowStyle = 'normal';
        options.Interpreter = 'tex';
        nameS = 'VELOCITY SELECTION';
        promptS = {'Constant velocity value for the selected segment:'};
        defaultS = {'0'};
        answerS = inputdlg(promptS,nameS,1,defaultS,options);
        valS = str2double(answerS{1}); 
        [~,IVc1] = min(abs(t-tc1));
        [~,IVc2] = min(abs(t-tc2));
        MV(IVc1:IVc2,2) = valS;
        delete(pp2);
        
    else
        
        Ifig = 1;
    
    end
    
    close(fig1);
    
end

delete(pp1); delete(txt1);

PluVel = [MR1 MV(:,2)];

mensave = menu('DO YOU WANT TO SAVE THE RAINFALL/VELOCITY FILE?','YES','NO');
if mensave == 1
    [filesa, pathsa] = uiputfile( ...
       {'*.mat','MAT-files (*.mat)'}, ...
        'SAVE RAINFALL/VELOCITY FILE', 'PluVel.mat');
    filesa = fullfile(pathsa,filesa);
    if ischar(filesa)
        save(filesa,'PluVel');
    end
end


%% Ancillary functions 

function plotRV(MR1,MR7,MV,dl1,dl2)
% Plot  of rainfall and velocity data on subplots
%
subplot(2,1,1); 
plot(MV(:,1),MV(:,2)); 
datetick('x',28); grid on; 
ylabel('\itVelocity \rm(m/d)');
xlim([dl1 dl2]);
%
subplot(2,1,2); 
plot(MR1(:,1),MR1(:,2),'b'); hold on; plot(MR7(:,1),MR7(:,2),'r'); hold off; 
datetick('x',28); grid on; legend('CR_1','CR_7');
ylabel('\itDate'); ylabel('\itCumulative rainfall \rm(mm)');
xlim([dl1 dl2]);